// pages/detail/detail.js

const mixins = require('../../mixins/forum')
const common = require('../../mixins/common')

import deviceUtil from "../../linui/utils/device-util";
import config from "../../api/config";
let videoAd = null
var a, e, app = getApp();
const options = {

  /**
   * 页面的初始数据
   */
  data: {
    comments: [],
    imagesubject: [],
    isInput: true,
    advert: app.globalData.advert,
    rwad: app.globalData.advert.rewardedVideoAd,
    page: 1,
    mask: true,
    maskClosable: true,
    voiceshow: false,
    audio_time: 0,
    is_complete_voice: !1,
    voiceshow: false,
    recording_status: "no_recording",
    deg: 0,
    progressWidth: 300,
    isIphoneX: app.globalData.isIphoneX,
    tabindex1: 1000,
    showPassword: false,
    baidupsw: "****",
    currentConfig: {
      show: false,
      transition: true,
      zIndex: 99,
      locked: false,
      direction: 'bottom',
      arcRadius: 18,
      maxHeight: 600,
      minHeight: 600,
      opacity: 0.4
    },
    audioInfo: {
      isPlaying: false,
      progress: 0
    },
    shareActionsheet: {
      closeOnClickOverlay: !0,
      componentId: "shareActionsheet",
      actions: [{
        name: "海报",
        className: "action-class",
        loading: !1,
        icon: "/image/share_icon1.svg",
        iconClassName: "down-icon"
      }, {
        name: "分享给朋友",
        openType: "share",
        icon: "/image/share_icon2.svg",
        iconClassName: "wc-icon"
      }]
    },
    emojiChars: ["😀", "😁", "😂", "😃", "😄", "😅", "😆", "😉", "😊", "😋", "😎", "😍", "😘", "😗", "😙", "😚", "☺", "😇", "😐", "😑", "😶", "😏", "😣", "😥", "😮", "😯", "😪", "😫", "😴", "😌", "😛", "😜", "😝", "😒", "😓", "😔", "😕", "😲", "😷", "😖", "😞", "😟", "😤", "😢", "😭", "😦", "😧", "😨", "😬", "😰", "😱", "😳", "😵", "😡", "😠", "👦", "👧", "👨", "👩", "👴", "👵", "👶", "👱", "👮", "👲", "👳", "👷", "👸", "💂", "🎅", "👰", "👼", "💆", "💇", "🙍", "🙎", "🙅", "🙆", "💁", "🙋", "🙇", "🙌", "🙏", "👤", "👥", "🚶", "🏃", "👯", "💃", "👫", "👬", "👭", "💏", "💑", "👪", "💪", "👈", "👉", "☝", "👆", "👇", "✌", "✋", "👌", "👍", "👎", "✊", "👊", "👋", "👏", "👐", "✍", "👣", "👀", "👂", "👃", "👅", "👄", "💋", "👓", "👔", "👕", "👖", "👗", "👘", "👙", "👚", "👛", "👜", "👝", "🎒", "💼", "👞", "👟", "👠", "👡", "👢", "👑", "👒", "🎩", "🎓", "💄", "💅", "💍", "🌂"],
    showEmoji: !1,
    inputValue: "",
    picturePath: "",
    keyboardHeight: 400,
    isIOS: !1,
    textNum: 0,
    menus: [{
      icon: "/image/edit_page_upload_pictures.png",
      text: "图片"
    }, {
      icon: "/image/edit_page_upload_record.png",
      text: "语音"
    }],
    hiddenAll: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id,
      type: options.type
    })
    this.data.manager = wx.getBackgroundAudioManager();
    this.getForumDetails();
    this.getPostsComments({
      id: options.id,
      page: this.data.page,
      order: 'desc'
    });
    if (this.data.rwad !== "") {
      this.onLoadRewardedVideoAd();
    }
  },


  onLoadRewardedVideoAd: function () {
    let that = this
    let datetime = Date.now()
    let expired = wx.getStorageSync('vd_expire')
    let videoAdLogs = wx.getStorageSync('videoAdLogs') || [];
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: that.data.rwad
      })
      videoAd.onLoad(() => {
        console.log('onLoad Video Ad')
      })
      videoAd.onError((err) => {
        console.log(err);
      })
      videoAd.onClose((res) => {
        console.log(res)
        if (res && res.isEnded) {
          that.setData({
            we_video_ad: false
          })
          if (this.data.isNetLink == true) {
            if (this.data.buttontype == 1) {
              this.setData({
                showPassword: true,
              })
            } else {
              this.navigateToBaidu();
            }
          }
        } else {
          if (!expired) {
            wx.setStorageSync('vd_expire', datetime + 86400)
          } else if (expired < datetime) {
            wx.removeStorageSync('videoAdLogs')
            wx.setStorageSync('vd_expire', datetime + 86400)
            videoAdLogs = []
          }
          if (videoAdLogs.indexOf(that.data.id) == -1) {
            videoAdLogs.unshift(that.data.id)
          }
          wx.setStorageSync('videoAdLogs', videoAdLogs)
        }
      })
    }

  },

  wxParseTagATap: function (e) {
    console.log(e);
    let url = e.currentTarget.dataset.src;
    wx.navigateTo({
      url: '/pages/view/view?url=' + url,
    })
  },

  navigateToBaidu: function () {
    var link = this.data.detail.meta.NetDisk[0].link + '/';
    var n = link.match(/\/s\/(.*?)\//);
    console.log(n);
    if (n) {
      var o = "pages/netdisk_share/share?surl=".concat(n[1], "&pwd=").concat(this.data.detail.baidupsw);
      console.log(n);
      wx.navigateToMiniProgram({
        appId: "wxdcd3d073e47d1742",
        path: o,
        extraData: {
          foo: "bar"
        },
        envVersion: "release",
        success: function (e) {}
      });
    } else wx.showToast({
      title: "暂不支持该打开链接，请复制到浏览器打开",
      icon: "none"
    });
  },

  copyLink: function () {
    wx.setClipboardData({
      data: this.data.detail.meta.NetDisk[0].link,
    })
  },

  openBaidu: function () {
    this.setData({
      isNetLink: true,
      buttontype: 0
    })
    if (this.data.rwad == '') {
      this.navigateToBaidu();
    } else {
      if (videoAd) {
        videoAd.show().catch(() => {
          // 失败重试
          videoAd.load()
            .then(() => videoAd.show())
            .catch(err => {
              console.log('激励视频 广告显示失败')
            })
        })
      }

    }

  },

  getPassword: function () {
    this.setData({
      isNetLink: true,
      buttontype: 1
    })
    if (this.data.rwad == '') {
      this.setData({
        showPassword: true,
      })
    } else {
      // 用户触发广告后，显示激励视频广告
      if (videoAd) {
        videoAd.show().catch(() => {
          // 失败重试
          videoAd.load()
            .then(() => videoAd.show())
            .catch(err => {
              console.log('激励视频 广告显示失败')
            })
        })
      }
    }
  },

  navToFeature: function (e) {
    let id = e.currentTarget.id;
    console.log(e);
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + id + '&type=' + this.data.type,
    })

  },

  changeHiddenStatus: function () {
    var t = this.data.hiddenAll;
    this.setData({
      hiddenAll: !t
    });
  },


  onMenuItem: function (t) {
    var a = t.currentTarget.dataset.index;
    switch (a) {

      case 0:
        this.addImage();
        break;

      case 1:
        this.bindVoice();
        break;

      default:
        e.log("publish => 暂无此多媒体类型");
    }
  },

  addImage: function () {
    this.uploadToMedia() // 上传到本地媒体库
  },


  uploadToMedia: function () {
    let that = this
    let images = this.data.imagesubject || []
    wx.chooseImage({
      count: 9,
      success: function (res) {
        for (let i = 0; i < res.tempFilePaths.length; i++) {
          let file = res.tempFilePaths[i];
          uploadMedia(file).then(res => {
              console.log(res);
              if (res.url) {
                images.push(res.url)
                console.log(images);
                if (images.length >= 9) {
                  return;
                } else {
                  that.setData({
                    imagesubject: images
                  })
                  wx.showToast({
                    title: '图片添加成功'
                  })
                }
              } else if (res.status == 500) {
                wx.showToast({
                  title: '图片添加失败'
                })
              }
            })
            .catch(err => {
              console.log(err)
              wx.showToast({
                title: '图片添加失败'
              })
            })
        }
      }
    })
  },

  shareClick: function () {
    this.setData({
      shareshow: true,
    })
  },

  goToEditImage: function (e) {
    let index = e.currentTarget.dataset.index;
    console.log(index);
    this.data.imagesubject.splice(index, 1);
    this.setData({
      imagesubject: this.data.imagesubject
    })

  },


  editTap: function (e) {
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    this.setData({
      delindex: index,
      showDialog: !this.data.showDialog,
      id: id,
    })

  },




  close: function () {
    this.data.maskClosable && (this.setData({
      showTextarea: !1,
      parent: 0,
      inputValue: "",
      picturePath: "",
      showEmoji: !1,
      voiceshow: false,
      title: '',
      parent: 0,
      commentValue: "回复内容...",
    }))
  },


  /**
   * 监听评论输入
   */
  bindWordLimit: function (e) {
    if (e.detail.value.length > 0) {
      this.setData({
        inputComment: e.detail.value,
        textNum: e.detail.value.length,
      })
    }
  },

  bindconfirm: function () {

    if (this.data.inputComment.lenth > 0) {
      this.setData({
        iscanpublish: true
      })
    }
  },

  /**
   * 删除已发布
   */

  bouncedDeleteTap: function (e) {
    let that = this;
    deletePost(this.data.id).then(res => {
      console.log(res);
      if (res.status == 200) {
        that.setData({
          bounced: false,
        })
        wx.showToast({
          title: '删除成功',
        })
        setTimeout(function () {
          wx.reLaunch({
            url: '/pages/index/index',
          })
        }, 1000)
      }
    }).catch(err => {
      if (err.message == "未授权登录用户,不能删除文章") {
        that.setData({
          bounced: false,
          showlogin: true,
          nologin: true
        })
      }
    })
  },

  editOrDeleteTap: function () {
    this.setData({
      showDialog: !this.data.showDialog,
      bounced: !this.data.bounced
    })
  },

  /**
   * 取消
   */
  onClickCancle: function () {
    this.setData({
      showDialog: !this.data.showDialog
    })

  },


  /**
   * 预览图片
   */

  previewImgFunc: function (e) {
    var images = []
    var imageslist = e.currentTarget.dataset.list;
    var src = e.currentTarget.dataset.src;
    for (var i = 0; i < imageslist.length; i++) {
      images.push(imageslist[i])
    }
    wx.previewImage({
      current: src,
      urls: images,
    })
  },


  /**
   * 视频播放
   */

  videoplay: function (url) {
    let that = this;
    wx.request({
      url: 'https://mall.guqule.com/mp/video.php',
      data: {
        url: url,
      },
      method: 'get',
      success: function (res) {
        console.log(res);
        if (res.data.status == 200) {
          that.setData({
            playurl: res.data.url
          })
        }
      }
    })

  },


  onImgOK(e) {
    this.imagePath = e.detail.path;
    wx.hideLoading();
    this.setData({
      imagePath: this.imagePath,
    });
  },

  /*** 隐藏画板 */
  hideshowPainter: function () {
    this.setData({
      showPainter: false,
    })
  },
  /**保存海报 */
  saveImage() {
    let that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success: function (e) {
        that.setData({
          showPainter: false,
        })
        wx.hideLoading();
        wx.showToast({
          title: '保存成功',
        })
      },
    });

  },



  /**
   * 评论语音播放
   */

  start: function (e) {
    let audio = e.currentTarget.dataset.src;
    let isindex = e.currentTarget.dataset.isindex;
    let index0 = e.currentTarget.dataset.tabidx0;
    let index1 = e.currentTarget.dataset.tabidx1;
    console.log(index1);
    let duration = parseInt(e.currentTarget.dataset.duration);
    this.data.manager.title = "录音播放"
    console.log(index0);
    this.setData({
      duration: duration,
      isindex: isindex,
      tabindex: index0,
      tabindex1: index1,
      state: "play"
    }), this.data.manager.src = audio, this.data.ing ? this.data.manager.play() : (this.data.ing = !0, this.data.manager.title = "录音播放",
      this.data.manager.onEnded(this.onEnd));
  },
  /**
   * 评论语音暂停
   */
  pause: function () {
    this.data.manager.stop(), this.data.ing = !1, this.setData({
      state: "pause",
    });
  },

  onEnd: function () {
    this.setData({
      audioTime: 0,
      state: "pause",
      dragging: !1,
      ing: !1
    });
  },
  /**
   *  跳转详情页
   */

  /**
   * 回复某人
   */

  replyComment: function (e) {
    let parent = e.currentTarget.dataset.parent
    let reply = e.currentTarget.dataset.reply
    this.setData({
      parent: parent,
      modalTarget: 'comment',
      showTextarea: true,
      commentValue: " 回复 " + reply + ":",
    })
  },

  gotoDetail: function (e) {
    console.log(e);
    let id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + id,
    })
  },


  /**
   * 获取相关文章
   */

  getRelateForums: function (id) {
    getRelateForum(id).then(res => {
      let args = [];
      args.relatePost = res;
      this.setData(args)
    })

  },


  onInputChange: function (t) {
    var a = t.detail.value;
    this.setData({
      inputValue: a
    });
  },
  onInputFocus: function (t) {
    console.log("comment-dialog => 输入框获取焦点"), console.log(t), this.data.showEmoji = !1;
    var a = wx.getSystemInfoSync(),
      e = parseInt(750 * t.detail.height / a.windowWidth);
    e > 0 && this.data.keyboardHeight != e && (this.data.keyboardHeight = e);
  },
  onEmojiClick: function () {
    this.data.showEmoji ? this.setData({
      showEmoji: !1
    }) : this.setData({
      showEmoji: !0,
      keyboardHeight: this.data.keyboardHeight
    });
  },

  stopTouch: function (t) {},
  onEmojiText: function (t) {
    var a = t.currentTarget.dataset.index;
    this.data.inputValue = this.data.inputValue + this.data.emojiChars[a], this.setData({
      inputValue: this.data.inputValue
    });
  },
  onImageChoose: function () {
    var t = this;
    wx.chooseImage({
      count: 1,
      sizeType: ["compressed"],
      success: function (a) {
        var e = a.tempFilePaths[0];
        console.log("comment-dialog => " + e), t.setData({
          picturePath: e
        });
      }
    });
  },

  /**
   * 关闭评论框
   */

  closeCommentary: function () {
    this.setData({
      showTextarea: false,
      voiceshow: false
    });
  },

  /**
   * 图片排序
   */

  imgPrev: function (t) {
    var e = t.currentTarget.dataset.index,
      a = this.data.imagesubject[e],
      i = this.data.imagesubject[e - 1];
    this.data.imagesubject[e] = i, this.data.imagesubject[e - 1] = a,
      this.setData({
        imagesubject: this.data.imagesubject
      });
  },
  imgNext: function (t) {
    var e = t.currentTarget.dataset.index,
      a = this.data.imagesubject[e],
      i = this.data.imagesubject[e + 1];
    this.data.imagesubject[e] = i, this.data.imagesubject[e + 1] = a,
      this.setData({
        imagesubject: this.data.imagesubject
      });
  },

  /**
   * 显示语音界面
   */

  bindVoice: function () {
    this.setData({
      voiceshow: !this.data.voiceshow
    })
  },



  /**
   * 录音开始
   */
  toRecordStart: function () {
    var o = this;
    o.setData({
      recording_status: "recording"
    }), app.recorderManager.start({
      duration: 6e4,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192e3,
      format: "mp3",
      frameSize: 50
    }), a = setInterval(function () {
      o.setData({
        audio_time: o.data.audio_time + 1
      }, function (a) {
        20 == o.data.audio_time && o.toRecordStop();
      });
    }, 1e3), e = setInterval(function () {
      o.setData({
        deg: o.data.deg + 1.8
      });
    }, 100);
  },
  /**
   * 录音结束
   */
  toRecordStop: function () {
    var o = this;
    if (clearInterval(a), clearInterval(e), o.data.audio_time < 5) return o.setData({
      audio_src: "",
      recording_status: "no_recording",
      audio_time: 0,
      deg: 0
    }), o.toast_none("录音时长不能少于5s", "", 2e3), t.recorderManager.stop(), void app.recorderManager.onStop(function (a) {});
    app.recorderManager.stop(), app.recorderManager.onStop(function (a) {
      console.log(a);
      o.setData({
        duration: a.duration,
        audio_src: a.tempFilePath,
        recording_status: "recording_suc"
      });
    });
  },
  /**选择语音 */
  select_audio: function () {
    this.audioToMedia();
  },

  /**播放语音 */
  playAudio: function () {
    var a = this;
    app.backgroundAudioManager.src = a.data.audio_src, app.backgroundAudioManager.title = "我的录音",
      a.setData({
        is_play: !0
      });
  },

  /**
   * 暂停语音
   */

  pauseAudio: function () {
    var a = this;
    app.backgroundAudioManager.pause(), a.setData({
      is_play: !1
    });
  },

  /**
   * 删除语音
   */

  del_audio: function (a) {
    var e = this;
    1 != a.currentTarget.dataset.flag ? e.setData({
      audio_src: "",
      recording_status: "no_recording",
      audio_time: 0,
      deg: 0
    }) : e.setData({
      audio_src: "",
      recording_status: "no_recording",
      is_complete_voice: !1,
      audio_time: 0,
      deg: 0
    });
  },





  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.initInnerAudioContext();

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let user = app.globalData.user
    if (!user) {
      user = '';
    }
    this.setData({
      user: user,
    })
  },

  /**
   * 点击评论
   */

  tapcomment: function () {
    var self = this;
    if (this.data.user) {
      this.setData({
        showTextarea: true,
        focus: true,
      })
      setTimeout(function () {
        self.setData({
          focus: true
        });
      }, 100);
    } else {
      self.data.currentConfig.show = true;
      self.setData({
        currentConfig: self.data.currentConfig,
      })
    }
  },

  gotouser: function (e) {
    let id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/user/user?id=' + id,
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.videoContext) {
      this.videoContext.stop();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      isBottom: true
    })
    if (!this.data.isLastPage) {
      this.getPostsComments({
        id: this.data.id,
        page: this.data.page
      })
    }
  },



  bindReadMore: function () {
    let platform = this.data.platform
    if (platform == 'devtools') {
      console.log("开发工具不支持显示激励视频");
    } else if (videoAd) {
      videoAd.show().catch(() => {
        videoAd.load().then(() => videoAd.show())
          .catch(err => {
            console.log('激励视频广告显示错误', err);
          })
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    return {
      title: this.data.detail.title.rendered,
      path: '/pages/detail/detail?id=' + this.data.detail.id + "&type=" + this.data.type,
      imageUrl: this.data.detail.meta.thumbnail,
      success: (res) => {
        console.log("转发成功", res);
      },
      fail: (res) => {
        console.log("转发失败", res);
      }
    }
  },
  onShareTimeline: function (res) {
    return {
      title: this.data.detail.title.rendered,
      query: 'id=' + this.data.detail.id + "&type=" + this.data.type,
      imageUrl: this.data.detail.meta.thumbnail //图片地址
    }
  }
}

common(options);
mixins(options);
Page(options);